﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using UnityEngine.SceneManagement;

public class MovementControllerScript : MonoBehaviour
{
    private GameObject target;

    private float TouchTime;
    private float speed;

    Vector3 touchPosWorld;

    // Use this for initialization
    void Start()
    {
        speed = 0.12f;
        target = GameObject.Find("Player");
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount > 0)
        {
            touchPosWorld = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPos = new Vector2(touchPosWorld.x, touchPosWorld.y);
            if (GetComponent<BoxCollider2D>() == Physics2D.OverlapPoint(touchPos))
            {

                if (Input.GetTouch(0).phase == TouchPhase.Began)
                {
                    TouchTime = Time.time;
                }

                if (Input.GetTouch(0).phase == TouchPhase.Ended || Input.GetTouch(0).phase == TouchPhase.Canceled)
                {
                    if (Time.time - TouchTime <= 0.5)
                    {
                        target.GetComponent<PlayerControllerScript>().JumpPlayer();
                    }
                }

                if (Input.touchCount > 0 && (Input.GetTouch(0).phase == TouchPhase.Began || Input.GetTouch(0).phase == TouchPhase.Moved))
                {
                    if (touchPosWorld.x <= target.transform.position.x)
                    {
                        target.transform.position = new Vector3(target.transform.position.x - speed, target.transform.position.y, target.transform.position.z);
                        target.GetComponent<SpriteRenderer>().flipX = true;
                    }

                    if (touchPosWorld.x >= target.transform.position.x)
                    {
                        target.transform.position = new Vector3(target.transform.position.x + speed, target.transform.position.y, target.transform.position.z);
                        target.GetComponent<SpriteRenderer>().flipX = false;
                    }
                }
                else if (Input.GetTouch(0).phase == TouchPhase.Ended || Input.GetTouch(0).phase == TouchPhase.Canceled)
                {

                }
            }
        }else
        {

        }
    }
}
